package com.app.bimo.library_db.helper;

import com.app.bimo.commonbusiness.util.DataUtil;
import com.app.bimo.library_db.SearchHistory;
import com.app.bimo.library_db.dao.DaoSession;
import com.app.bimo.library_db.dao.SearchHistoryDao;

import java.util.ArrayList;
import java.util.List;

public class SearchHistoryHelper {

    private static volatile SearchHistoryHelper sInstance;
    private static DaoSession daoSession;
    private static SearchHistoryDao searchHistoryDataDao;

    public static SearchHistoryHelper getsInstance() {
        if (sInstance == null) {
            synchronized (SearchHistoryHelper.class) {
                if (sInstance == null) {
                    sInstance = new SearchHistoryHelper();
                    daoSession = DaoDbHelper.getInstance().getSession();
                    searchHistoryDataDao = daoSession.getSearchHistoryDao();
                }
            }
        }
        return sInstance;
    }

    private SearchHistoryHelper() {

    }

    /**
     * 保存搜索历史
     *
     * @param searchHistoryData
     */
    public void saveHistory(SearchHistory searchHistoryData) {
        delHistoryOther(searchHistoryData.getUid());
        searchHistoryDataDao.insertOrReplace(searchHistoryData);

    }

    /**
     * 删除搜索历史
     *
     * @param searchHistoryData
     */
    public void delHistory(SearchHistory searchHistoryData) {
        searchHistoryDataDao.delete(searchHistoryData);
    }

    /**
     * 删除搜索历史
     *
     * @param
     */
    public void delHistoryAll() {
        searchHistoryDataDao.deleteAll();
    }

    /**
     * 删除搜索历史
     *
     * @param
     */
    public void delHistoryOther(String uid) {
        List<SearchHistory> list = findAll(uid);
        if (list != null && list.size() >= 10) {
            for (int i = list.size() - 1; i > 8; i--) {
                searchHistoryDataDao.deleteInTx(list.get(i));
            }
        }
    }

    /**
     * 查询5条信息
     *
     * @return
     */
    public List<SearchHistory> findAll(String uid) {
        if (DataUtil.isEmpty(uid)) {
            return new ArrayList<>();
        }
        return searchHistoryDataDao.queryBuilder().where(SearchHistoryDao.Properties.Uid.eq(uid)).orderDesc(SearchHistoryDao.Properties.CreatTime).list();
    }

}
